package com.dragon.modules.yuegou.service.impl.merchant;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.merchant.MerchantApplyEntity;
import com.dragon.modules.yuegou.entity.merchant.MerchantEntity;
import com.dragon.modules.yuegou.enums.code.MerchantCode;
import com.dragon.modules.yuegou.enums.merchant.MerchantApplyCheckStatus;
import com.dragon.modules.yuegou.enums.merchant.MerchantMerchantType;
import com.dragon.modules.yuegou.enums.merchant.MerchantStatus;
import com.dragon.modules.yuegou.enums.merchant.MerchantType;
import com.dragon.modules.yuegou.mapper.merchant.MerchantApplyMapper;
import com.dragon.modules.yuegou.model.busd.District;
import com.dragon.modules.yuegou.model.merchant.Merchant;
import com.dragon.modules.yuegou.model.merchant.MerchantApply;
import com.dragon.modules.yuegou.query.merchant.MerchantApplyQuery;
import com.dragon.modules.yuegou.service.busd.DistrictService;
import com.dragon.modules.yuegou.service.merchant.BankService;
import com.dragon.modules.yuegou.service.merchant.MerchantApplyService;
import com.dragon.modules.yuegou.service.merchant.MerchantService;
import com.dragon.modules.yuegou.utils.PageToResultUtils;
import com.dragon.modules.yuegou.web.Check;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户信息申请表 服务实现
 *
 * @author pbuilder generated
 * @date 2021-11-18 11:39:56
 * @version 2.0
 */
@Service("merMerchantApplyService")
public class MerchantApplyServiceImpl
		extends ServiceImpl<MerchantApplyMapper, MerchantApplyEntity>
		implements MerchantApplyService {

	@Autowired
	private MerchantService merchantService;

	@Autowired
	private DistrictService districtService;
	
	@Autowired
	private BankService bankService;

	@Override
	public IPage<MerchantApply> pageMerchantApply(PageRequest page, MerchantApplyQuery query){
		return  page(PageToResultUtils.resultToPage(page),query.toQueryWrapper());
	}

	@Override
	public MerchantApply saveMerchantApply(MerchantApply apply){
		Check.notEmpty(apply.getBusdId(),"商圈id不能为空");
		Check.notEmpty(apply.getMerchantName(),"商户名称不能为空");
		Check.notEmpty(apply.getContactName(),"联系人不能为空");
		Check.notEmpty(apply.getContactMobile(),"联系电话不能为空");
		Check.notNull(apply.getMerchantType(),"商户类型不能为空");
		Check.notNull(apply.getStartBusinessTime(),"营业开始时间不能为空");
		Check.notNull(apply.getEndBusinessTime(),"营业结束时间不能为空");
		Check.notEmpty(apply.getMerchantLogo(),"LGOG图不能为空");
		Check.notEmpty(apply.getMerchantBackgroundImg(),"背景图不能为空");
		//判断是否重复申请
		if (StringUtils.isNotEmpty(apply.getApplyBy())){
			MerchantApplyQuery query = new MerchantApplyQuery();
			query.applyBy().eq(apply.getApplyBy());
			List<MerchantApplyCheckStatus> checkStatuses = new ArrayList<>();
			checkStatuses.add(MerchantApplyCheckStatus.UNCHECK);
			checkStatuses.add(MerchantApplyCheckStatus.SUCCESS);
			query.checkStatus().in(checkStatuses);
			List<MerchantApplyEntity> merchantApplyList = list(query.toQueryWrapper());
			if (CollectionUtils.isNotEmpty(merchantApplyList) && StringUtils.isEmpty(apply.getId())){
				throw new DragonException(MerchantCode.APPLY_EXIST);
			}
		}
		MerchantApplyQuery query = new MerchantApplyQuery();
		query.busdId().eq(apply.getBusdId());
		query.merchantName().eq(apply.getMerchantName());
		List<MerchantApplyCheckStatus> checkStatuses = new ArrayList<>();
		checkStatuses.add(MerchantApplyCheckStatus.UNCHECK);
		checkStatuses.add(MerchantApplyCheckStatus.SUCCESS);
		query.checkStatus().in(checkStatuses);
		List<MerchantApplyEntity> merchantApplyList = list(query.toQueryWrapper());
		if (CollectionUtils.isNotEmpty(merchantApplyList)){
			if (merchantApplyList.size() > 1){
				throw new DragonException(MerchantCode.APPLY_NAME_EXIST);
			}
			if (!merchantApplyList.get(0).getId().equals(apply.getId())){
				throw new DragonException(MerchantCode.APPLY_NAME_EXIST);
			}
		}

		if (StringUtils.isNotEmpty(apply.getId())){
			updateById(apply);
		}else {
			save(apply);
		}
		return apply;
	}

	@Override
	public MerchantApply getMerchantApplyById(String id){
		MerchantApply apply = new MerchantApply(getById(id));
		if(StringUtils.isNotEmpty(apply.getMerchantId())) {
    		MerchantEntity merchant =merchantService.getById(apply.getMerchantId());
    		apply.setMerchantSort(merchant.getMerchantSort());
		}
		return apply;
	}

	@Override
	public MerchantApply getMerchantApplyByApplyBy(String applyBy){
		MerchantApplyQuery query = new MerchantApplyQuery();
		query.applyBy().eq(applyBy);
		List<MerchantApplyCheckStatus> checkStatuses = new ArrayList<>();
		checkStatuses.add(MerchantApplyCheckStatus.UNCHECK);
		checkStatuses.add(MerchantApplyCheckStatus.SUCCESS);
		checkStatuses.add(MerchantApplyCheckStatus.FAILURE);
		query.checkStatus().in(checkStatuses);
		List<MerchantApplyEntity> merchantApplyList = list(query.toQueryWrapper()).stream().sorted(Comparator.comparing(MerchantApplyEntity::getCreatedTime).reversed()).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(merchantApplyList)){
			return new MerchantApply(merchantApplyList.get(0));
		}
		return null;
	}


	@Override
	@Transactional
	public void checkApply(MerchantApply apply){
		Check.notEmpty(apply.getId(),"申请id不能为空");
		Check.notEmpty(apply.getCheckBy(),"审核人不能为空");
		Check.notEmpty(apply.getCheckOpinion(),"审核原因不能为空");
		Check.notNull(apply.getCheckStatus(),"审核状态不能为空");
		MerchantApply merchantApply = getMerchantApplyById(apply.getId());
		if (merchantApply==null || StringUtils.isEmpty(merchantApply.getId())){
			throw new DragonException(MerchantCode.APPLY_NOT_EXIST);
		}

		if (MerchantApplyCheckStatus.SUCCESS.equals(merchantApply.getCheckStatus())){
			throw new DragonException(MerchantCode.CHECK_SUCCSEE);
		}
		//基础信息
		merchantApply.setMerchantName(apply.getMerchantName());
		merchantApply.setMerchantType(apply.getMerchantType());
		merchantApply.setContactName(apply.getContactName());
		merchantApply.setContactMobile(apply.getContactMobile());
		merchantApply.setStartBusinessTime(apply.getStartBusinessTime());
		merchantApply.setEndBusinessTime(apply.getEndBusinessTime());
		merchantApply.setRemarks(apply.getRemarks());
		merchantApply.setMerchantLogo(apply.getMerchantLogo());
		merchantApply.setMerchantBackgroundImg(apply.getMerchantBackgroundImg());
		
		//银行卡相关
		merchantApply.setBankCode(apply.getBankCode());
		merchantApply.setBankName(apply.getBankName());
		merchantApply.setEncBankNo(apply.getEncBankNo());
		merchantApply.setEncTrueName(apply.getEncTrueName());
		
		//业态楼栋相关
		merchantApply.setBtypeId(apply.getBtypeId());
		merchantApply.setBtypeSecondId(apply.getBtypeSecondId());
		merchantApply.setMerchantAcreage(apply.getMerchantAcreage());
		merchantApply.setLevel(apply.getLevel());
		merchantApply.setPartnership(apply.getPartnership());
		merchantApply.setMerchantSort(apply.getMerchantSort());
		merchantApply.setBuildingId(apply.getBuildingId());
		merchantApply.setFloorId(apply.getFloorId());
		merchantApply.setMerchantCode(apply.getMerchantCode());
		merchantApply.setContactAddress(apply.getContactAddress());
			
		//审核相关
		merchantApply.setCheckTime(LocalDateTime.now());
		merchantApply.setCheckBy(apply.getCheckBy());
		merchantApply.setCheckStatus(apply.getCheckStatus());
		merchantApply.setCheckOpinion(apply.getCheckOpinion());

		//审核成功 需要新建铺位
		if (MerchantApplyCheckStatus.SUCCESS.equals(apply.getCheckStatus())){
			District district = districtService.getDistrictById(apply.getBusdId());
			Merchant merchant = new Merchant();
			merchant.setBankCode(apply.getBankCode());
			merchant.setBankName(apply.getBankName());
			merchant.setEncBankNo(apply.getEncBankNo());
			merchant.setEncTrueName(apply.getEncTrueName());
			merchant.setBcName(district.getBcName());
			merchant.setFrdcount(0);
			merchant.setGirlIndex(0);
			merchant.setLatitude(district.getLatitude().toString());
			merchant.setLongitude(district.getLongitude().toString());
			merchant.setPreferential(0);
			merchant.setQrCodeStatus(false);
			merchant.setSales(BigDecimal.ZERO);
			merchant.setStatus(MerchantStatus.NORMAL);
			merchant.setSum(0);
			merchant.setBtypeId(apply.getBtypeId());
			merchant.setBtypeSecondId(apply.getBtypeSecondId());
			merchant.setLevel(apply.getLevel());
			merchant.setPartnership(apply.getPartnership());
			merchant.setMerchantSort(apply.getMerchantSort());
			merchant.setMerchantAcreage(apply.getMerchantAcreage());
			merchant.setUsername(merchantApply.getApplyMobile());
			merchant.setType(MerchantType.COMMON);
			merchant.setVoiceCof(false);
			merchant.setVolume(0);
			merchant.setBuildingId(merchantApply.getBuildingId());
			merchant.setBusdId(merchantApply.getBusdId());
			merchant.setContactMobile(merchantApply.getContactMobile());
			merchant.setContactName(merchantApply.getContactName());
			merchant.setCreatedBy(merchantApply.getCheckBy());
			merchant.setCreatedTime(LocalDateTime.now());
			merchant.setDel(false);
			merchant.setEndBusinessTime(merchantApply.getEndBusinessTime());
			merchant.setStartBusinessTime(merchantApply.getStartBusinessTime());
			merchant.setFloorId(merchantApply.getFloorId());
			merchant.setMerchantAcreage(merchantApply.getMerchantAcreage());
			merchant.setStatisticsFreeNum(0);
			merchant.setStatistics(false);
			merchant.setRemarks(merchantApply.getRemarks());
			merchant.setMerchantType(MerchantMerchantType.from(merchantApply.getMerchantType().getCode()));
			merchant.setMerchantName(merchantApply.getMerchantName());
			merchant.setMerchantLogo(merchantApply.getMerchantLogo());
			merchant.setMerchantCode(merchantApply.getMerchantCode());
			merchant.setMerchantBackgroundImg(merchantApply.getMerchantBackgroundImg());
			merchant.setPassword("123456");
			merchant.setConfirmPassword("123456");
			merchant.setContactAddress(apply.getContactAddress());
			String merchantId =merchantService.saveMerchant(merchant);
			merchantApply.setMerchantId(merchantId);
		}
		saveMerchantApply(merchantApply);

	}
}